package com.cskaoyan.thread02.deadlock.edition1;

/*
        死锁问题的第一种解决方案:  调整加锁顺序，让多个线程的加锁顺序相同
 */
public class Demo1 {
    // lockA锁
    static Object lockA = new Object();
    // lockB锁
    static Object lockB = new Object();


    public static void main(String[] args) {

        ABThread abThread = new ABThread();
        BAThread baThread = new BAThread();

        abThread.start();
        baThread.start();
    }
}

/*
        先加A锁在加B锁
        1. 先对lockA锁加锁，访问共享变量
        2. 在对lockB锁加锁，访问打印机
 */
class ABThread extends Thread {

    @Override
    public void run() {
        synchronized (Demo1.lockA) {
            // 访问共享变量, 计算
            System.out.println("ABThread lockA");
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (Demo1.lockB) {
                // 访问打印机，打印结果
                System.out.println("ABThread lockB");
            }
        }
    }
}

/*
        先加B锁在加A锁
        1. 先对lockB锁加锁，先获取打印机的访问
        2. 在对lockA锁加锁，访问共享变量，打印计算结果
  */
class BAThread extends Thread {

    @Override
    public void run() {
        synchronized (Demo1.lockA) {
            // 访问共享变量，计算结果
            System.out.println("BAThread lockA");
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (Demo1.lockB) {
                // 访问打印机
                System.out.println("BAThread lockB");
            }
        }
    }
}
